﻿using Glimpse.Core.Framework;
using Glimpse.Core.Extensibility;
using System.Collections.Generic;
using System.Linq;

namespace GlimpseWcf.Server
{
    public class WcfFrameWorkProvider : IFrameworkProvider
    {
        public string TabHtml { get; set; }
        public byte[] byteResponse;
        public Dictionary<string, string> _cookiesToReturn = new Dictionary<string, string>();

        public WcfFrameWorkProvider(ILogger logger)
        {
            Logger = logger;
            HttpRequestStore.Set("byteResponse", new byte[0]);
            HttpRequestStore.Set("httpResponse", "");
        }

        internal OperationContextWrapper Context
        {
            get { return OperationContextWrapper.Current; }
        }

        public IDataStore HttpRequestStore
        {
            get { return new DictionaryDataStoreAdapter(Context.Items); }
        }

        public IDataStore HttpServerStore
        {
            get { return new WcfDataStore(); }
        }

        public void InjectHttpResponseBody(string htmlSnippet)
        {
            HttpRequestStore.Set("TabHtml",htmlSnippet);
        }

        public IRequestMetadata RequestMetadata
        {
            get { return new WcfRequestMetadata(Context); }
        }

        public object RuntimeContext
        {
            get { return Context; }
        }

        public void SetCookie(string name, string value)
        {
            _cookiesToReturn.Add(name, value);
        }

        public void SetHttpResponseHeader(string name, string value)
        {
        }

        public void SetHttpResponseStatusCode(int statusCode)
        {
        }

        public void WriteHttpResponse(string content)
        {
            HttpRequestStore.Set("httpResponse", HttpRequestStore.Get("httpResponse") + "\r\n" + content);
        }

        public void WriteHttpResponse(byte[] content)
        {
            HttpRequestStore.Set("byteResponse", ((byte[])HttpRequestStore.Get("byteResponse")).Concat(content).ToArray());
        }

        public ILogger Logger { get; set; }
    }
}